home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 13224 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.0 KB

  1. Path: beta.nedernet.nl!usenet
  2. From: jos@and.nl (Jos A. Horsmeier)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Recursion
  5. Date: 5 Apr 1996 08:04:57 GMT
  6. Organization: AND Operations Research B.V.
  7. Message-ID: <4k2k79$ka9@beta.nedernet.nl>
  8. References: <31624BC2.70D2@sooner.net>
  9. NNTP-Posting-Host: klepzeiker.and.nl
  10. Mime-Version: 1.0
  11. Content-Type: Text/Plain; charset=ISO-8859-1
  12. X-Newsreader: WinVN 0.99.5
  13.  
  14. In article <31624BC2.70D2@sooner.net>, edwbush@sooner.net wrote:
  15.  
  16. |I am trying to construct a C function that will recursively convert
  17. |a string such as "1234" into it's integer equivelant (1234).
  18.  
  19. I suspect this to be a homework problem, but, on the other hand, I've
  20. seen replies suggesting the following too:
  21.  
  22. - using malloc() to store a temporary buffer;
  23. - modifying the character string argument;
  24. - using the pow() function;
  25. - using a char buf[100] temporary buffer.
  26.  
  27. Is it because it's Friday? ;-) Normally when it's Friday I turn completely
  28. silly (it's got something to do with the weekend; dunno ...) but I didn't
  29. expect you ladies and gentlemen to pick me as a role model ;-)
  30.  
  31. How about the following simple observation:
  32.  
  33. let S be a string s_0, s_1 ... s_n, then the integer value of this
  34. string happens to be: atoir(S)= 10*atoir(s_0, s_1, ... s_n-1)+s_n-'0'
  35. if n contains more than one character, otherwise the result is simply
  36. s_0-'0' if the string S contains one characters, otherwise the result
  37. is undefined ...
  38.  
  39. Sprinkling in some C lingo, we get something like this:
  40.  
  41. int atoir(char* S, int n) {
  42.  
  43.     if (n < 0)            /* undefined result */
  44.         return rand();        /* slightly silly ... */
  45.     else if (n == 0)        /* just one digit */
  46.         return S[0]-'0';
  47.     else                /* plunge into recursion */
  48.         return 10*atoir(S, n-1)+ S[n]-'0';
  49. }
  50.  
  51. Here's the wrapper for the function above:
  52.  
  53. int atoiwrap(char* S) {
  54.  
  55.     return atoi(S, strlen(S)-1);
  56. }
  57.  
  58. If you ladies and gentlemen will excuse me now, then I'll turn back to
  59. my normal silly-Friday-mood ;-)
  60.  
  61. kind regards,
  62.  
  63. Jos aka jos@and.nl (slightly silly on the right side; 12 points)
  64. -- 
  65. Atnwgqkrl gy zit vgksr, ug qshiqwtzoeqs!
  66.  
  67.